package com.lagouedu.rabbitmq_demo.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.additional.update.impl.UpdateChainWrapper;
import com.lagouedu.rabbitmq_demo.entity.OrderEntity;
import com.lagouedu.rabbitmq_demo.mapper.OrderMapper;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class OrderService{

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Resource
    private OrderMapper orderMapper;

    public Map order(Map product){
        Map<String,Object> result = new HashMap<>();
        // 保存订单数据
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderId((Integer) product.get("orderId"));
        orderEntity.setProductId((Integer) product.get("productId"));
        orderEntity.setStatus(0);
        orderMapper.insert(orderEntity);
        // 用户下单后向ttl队列中发送消息
        // 商品Id 、商品名称、商品价格
        amqpTemplate.convertAndSend("ex.ttl", "key.ttl",product);
        result.put("code",1);
        result.put("msg","下单成功,请在10s内完成付款");
        return result;
    }

    public int getOrderStatus(Integer orderId){
        OrderEntity orderEntity = orderMapper.selectById(orderId);
        if(orderEntity!=null){
            return orderEntity.getStatus();
        }
        return 3; //没有该订单状态 0:未支付 1 已支付 2 已取消
    }

    // 修改订单状态
    public int updateOrderStatus(Integer orderId, Integer status){
        UpdateWrapper<OrderEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", status);
        updateWrapper.eq("order_id", orderId);
        return orderMapper.update(null, updateWrapper);
    }
}
